package org.class2table.core.util;

import org.class2table.core.Class2TableException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class DataSourceUtil {

    private static List<Connection> connectionList = new ArrayList<>();

    public static Connection getConnection(String url, String username, String password) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection(url, username, password);
        connectionList.add(connection);
        return connection;
    }

    public static void release() {
        for (Connection connection : connectionList) {
            if (Objects.nonNull(connection)) {
                try {
                    connection.close();
                } catch (Exception e) {
                    throw new Class2TableException("close connection failed!", e);
                }
            }
        }
    }

}
